import app from "./server.ts";
import { qrcode } from "@libs/qrcode";


function getLocalIP(port: number): string | null {
  for (const iface of Deno.networkInterfaces()) {
    if (
      iface.family === "IPv4" &&
      !iface.address.startsWith("127.") &&
      !iface.name.startsWith("VMware") &&
      !iface.name.startsWith("vEthernet")
    ) {
      console.log(`局域网访问: %chttp://${iface.address}:${port}`, 'text-decoration: underline; color: #00f;');
      return `http://${iface.address}:${port}`;
    }
  }
  return null;
}

// 自动打开浏览器的函数
async function openBrowser(url: string) {
  const os = Deno.build.os;
  let command: Deno.Command;

  if (os === "windows") {
    // Windows: 使用 cmd /c start
    command = new Deno.Command("cmd", {
      args: ["/c", "start", "", url],
    });
  } else if (os === "darwin") {
    // macOS
    command = new Deno.Command("open", { args: [url] });
  } else if (os === "linux") {
    // Linux
    command = new Deno.Command("xdg-open", { args: [url] });
  } else {
    console.warn("不支持的操作系统，无法自动打开浏览器");
    return;
  }

  try {
    await command.spawn().status;
  } catch (error) {
    console.error("打开浏览器失败:", error);
  }
}

// Learn more at https://docs.deno.com/runtime/manual/examples/module_metadata#concepts
if (import.meta.main) {
  const port = 8787;
  Deno.serve({ port }, app.fetch);
  const url = getLocalIP(port);
  if (url) {
    setTimeout(async () => {
      await openBrowser(url);
      qrcode(url, { output: "console", light: 'white', dark: '#4444bcff' });
    }, 500);
  }
}
